package com.easy.common.util.auth;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.easy.common.constant.AuthKeys;
import com.easy.common.constant.RegistProps;
import com.easy.common.constant.SysProps;
import com.easy.common.util.Utility;
import com.easy.common.util.file.FileUtility;

public class RegistUtility {

	private static final Logger log = Logger.getLogger("com.easy.util.auth.MYRegistUtility");

	public RegistUtility()
	{
	}

	public static String getMchineCode()
		throws Exception
	{
		if (SysProps.isWindows()){
			//return MYHardWare.getMachineCode(MYSysProps.getRootPath().substring(0, 3));
			//return EIHardWare.getMachineCode();
			return "";
		}
		if (SysProps.isLinux())
			return LinuxUtility.getMachineCode();
		else
			throw new Exception("Unsurported OS");
	}

	public static Map<String, Object> loadRegistFromPath(String fileName, String installDisk, String softId, String registOrg)
	{
		Map<String, Object> registMap = new HashMap<String, Object>();
		File file = new File(fileName);
		if (!file.exists())
			return registMap;
		if (file.isDirectory())
		{
			String fileList[] = file.list();
			for (int i = 0; i < fileList.length; i++)
			{
				String currFileName = fileList[i];
				if (currFileName.endsWith(".regist") || currFileName.endsWith(".install"))
				{
					String filePath = (new StringBuilder(String.valueOf(fileName))).append(File.separator).append(currFileName).toString();
					Map<String, Object> tmpMap = loadRegist(filePath, installDisk, softId, registOrg);
					Utility.copyMap(tmpMap, registMap);
				}
			}

		}
		return registMap;
	}

	public static Map<String, Object> loadRegist(String fileName, String installDisk, String softId, String registOrg)
	{
		Map<String, Object> registMap;
		registMap = new HashMap<String, Object>();
		File file = new File(fileName);

		if (!file.exists() || !file.isFile())
			return registMap;
		String machineCode;
		byte buf[];
		try
		{
			machineCode = getMchineCode();
			buf = FileUtility.loadFile2Bytes(fileName);
			if (buf == null)
				return registMap;
			String propStr = Authenticator.ciphDecryptBytes(buf);
			Utility.str2Map(propStr, registMap);
			List<String> keyList = new ArrayList<String>();
			for (Iterator<String> iKeys = registMap.keySet().iterator(); iKeys.hasNext();)
			{
				String key = (String)iKeys.next();

				if (!key.endsWith(".Didgist"))
				{
					String value = (String)registMap.get(key);
					String didgistKey = key+".Didgist";
					//(new StringBuilder(String.valueOf(key))).append(".Didgist").toString();
					String didgist = (String)registMap.get(didgistKey);
					
					if (didgist == null)keyList.add(key);
					else {
						try
						{
							if (!Authenticator.isValidRegist(AuthKeys.getMD5SaltLength(null), (new StringBuilder(String.valueOf(value))).append(machineCode).append(softId).append(registOrg).toString(), didgist))
							{
								keyList.add(key);
								keyList.add(didgistKey);
							}
							else
							{
								keyList.add(didgistKey);
							}
						}
						catch (Exception ex)
						{
							keyList.add(key);
						}
					}
				}
			}

			for (int i = 0; i < keyList.size(); i++)
			{
				String key = (String)keyList.get(i);
				registMap.remove(key);
			}

		}
		catch (Exception ex)
		{
			log.debug(ex.getMessage(), ex);
		}
		return registMap;
	}

	public static Map<String, Object> loadRegist(String fileName)
	{
		Map<String, Object> registMap;
		registMap = new HashMap<String, Object>();
		File file = new File(fileName);
		if (!file.exists() || !file.isFile())
			return registMap;
		try
		{
			byte buf[] = FileUtility.loadFile2Bytes(fileName);
			if (buf == null)return registMap;
			String propStr = Authenticator.ciphDecryptBytes(buf);
			Utility.str2Map(propStr, registMap);
			List<String> keyList = new ArrayList<String>();
			Iterator<String> iKeys = registMap.keySet().iterator();
			while( iKeys.hasNext())
			{
				String key = (String)iKeys.next();

				if (key.endsWith(".Didgist"))
					keyList.add(key);
			}
			for (int i = 0; i < keyList.size(); i++)
			{
				String key = (String)keyList.get(i);
				registMap.remove(key);
			}
		}
		catch (Exception ex)
		{
			log.debug(ex.getMessage(), ex);
		}
		return registMap;
	}

	public static boolean hasRegisted()
	{
		return !Utility.isNullorEmpty(RegistProps.getString("regist.org.my"));
	}

	public static boolean isExpired()
	{
		return remainDays() < 1;
	}

	public static int remainDays()
	{
		String installTimeStr;
		String installTimePassStr;
		try{
			installTimeStr = SysProps.getString("installTime");
			installTimePassStr = SysProps.getString("installTimePass");
			if (Utility.isNullorEmpty(installTimeStr) || Utility.isNullorEmpty(installTimePassStr))
				return 0;
			if (!Authenticator.isValidRegist(AuthKeys.getMD5SaltLength(null), installTimeStr, installTimePassStr))
				return 0;
			long installTime;
			long currTime;
			int evalueDate=0;
			installTime = Long.parseLong(installTimeStr);
			currTime = System.currentTimeMillis();
			String evalueDaysStr = SysProps.getString("evalueDays");
			String evalueDaysPass = SysProps.getString("evalueDaysPass");
			if (!Utility.isNullorEmpty(evalueDaysStr) && Authenticator.isValidRegist(AuthKeys.getMD5SaltLength(null), (new StringBuilder(String.valueOf(evalueDaysStr))).append(getMchineCode()).toString(), evalueDaysPass))
				evalueDate = Integer.parseInt(evalueDaysStr);
			if ((currTime - installTime) / 86400000 > (long)evalueDate)
				return 0;
			return evalueDate - (int)((currTime - installTime) / 86400000);
		}
		catch(Exception ex){
		}
		return 0;
	}

	public static int getUserCnt()
	{
		int defaultCnt=0;
		String userCntStr;
		String userCntPassStr;
		try{
			int maxUserCnt = RegistProps.getInt("user.cnt.my");
			if (maxUserCnt > 0)
				return maxUserCnt;
			defaultCnt = 30;
			userCntStr = SysProps.getString("maxUserCnt");
			userCntPassStr = SysProps.getString("maxUserCntPass");
			if (Utility.isNullorEmpty(userCntStr) || Utility.isNullorEmpty(userCntPassStr))
				return defaultCnt;
			if (!Authenticator.isValidRegist(AuthKeys.getMD5SaltLength(null), (new StringBuilder(String.valueOf(userCntStr))).append(getMchineCode()).toString(), userCntPassStr))
				return defaultCnt;
			int userCnt = Integer.parseInt(userCntStr);
			return userCnt;
		}
		catch(Exception ex){
		}
		return defaultCnt;
	}

}
